import axios from "axios";
import { useRouter } from "vue-router";

axios.interceptors.request.use(
  function (config) {
    if (localStorage.getItem("token")) {
      config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    }
    return config;
  },
  function (err) {
    return err;
  }
);

axios.interceptors.response.use(
  function (res) {
    if (res.data.code === 401) {
      console.error("无效token");
      localStorage.removeItem("token");
      useRouter().push("/login");
      return;
    } else if (res.data.code === 200) {
      // console.log(res.data);
      return res.data;
    }
  }
  // function (err) {
  //   try {
  //     localStorage.removeItem("token");
  //     useRouter().push("/login");
  //   } catch (err) {}
  // }
);
